<template>
  <el-drawer
    append-to-body
    destroy-on-close
    :size="size"
    :title="title"
    :visible.sync="drawer"
    @close="close"
  >
    <div v-if="drawer">
      <div class="header">
        <div class="left">
          <div class="text">{{ roomDetail.room_address }}</div>
          <div class="group">{{ roomDetail.group_name }}</div>
        </div>
        <div class="right">
          <el-button>水电记录</el-button>
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="入住详情" name="1">
          <div class="roomDetail">
            <div class="titleBox">
              <div class="title">
                <div class="titleName">入住人基本信息</div>
                <el-button
                  v-if="form.rent_status != 2"
                  class="edit"
                  type="text"
                  @click="editInfo"
                >
                  编辑
                </el-button>
              </div>
              <div v-if="form.rent_status != 2" class="btn">
                <el-button @click="addContract">添加合同</el-button>
                <el-button @click="outRoom">退房</el-button>
                <el-button @click="moreDate">续租</el-button>
              </div>
            </div>
            <div class="detail">
              <div class="textForm">
                <div class="label">
                  <div class="name">姓名</div>
                  <div class="value">
                    {{ info.customer_name }}
                  </div>
                </div>
                <div class="label">
                  <div class="name">证件号</div>
                  <div class="value">
                    {{ info.customer_idcard }}
                  </div>
                </div>
                <div class="label">
                  <div class="name">联系方式</div>
                  <div class="value">
                    {{ info.customer_mobile }}
                  </div>
                </div>
                <div class="label">
                  <div class="name">入住周期</div>
                  <div class="value">
                    {{ form.start_date }} 至 {{ form.end_date }}
                  </div>
                </div>
              </div>
            </div>
            <div class="titleBox">
              <div class="title">
                <div class="titleName">同住人信息</div>
                <el-button
                  v-if="form.rent_status != 2"
                  class="add"
                  @click="addCustomer"
                >
                  <i class="el-icon-circle-plus"></i>
                  添加同住人
                </el-button>
              </div>
            </div>
            <div class="customer">
              <div
                v-if="
                  form.customer_list instanceof Array &&
                  form.customer_list.length < 1
                "
                class="empty"
              >
                暂无同住人信息
              </div>
              <div v-else class="textList">
                <div
                  v-for="item in form.customer_list"
                  :key="item.id"
                  class="textBox"
                >
                  <div class="name">
                    姓名
                    <span>{{ item.customer_name }}</span>
                  </div>
                  <div class="mobile">
                    联系方式
                    <span>{{ item.customer_mobile }}</span>
                  </div>
                  <div v-if="form.rent_status != 2">
                    <el-button type="text" @click="editCustomer(item)">
                      编辑
                    </el-button>
                    <el-button
                      class="deleteBtn"
                      type="text"
                      @click="deleteCustomer(item)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="titleBox">
              <div class="title">
                <div class="titleName">合同信息</div>
              </div>
            </div>
            <div class="detail">
              <div v-if="form.contract_sn == ''" class="empty">
                暂无合同信息
              </div>
              <div v-else class="text">
                {{ form.contract_sn }}
              </div>
            </div>
            <div class="titleBox">
              <div class="title">
                <div class="titleName">房间备注</div>
                <el-button v-if="form.rent_status != 2" class="edit" type="text" @click="editDesc">
                  编辑
                </el-button>
              </div>
            </div>
            <div class="detail">
              <div v-if="form.rent_remark == ''" class="empty">暂无备注</div>
              <div v-else class="text">
                {{ form.rent_remark }}
              </div>
            </div>
            <div class="titleBox">
              <div class="title">
                <div class="titleName">视频图片</div>
                <el-button v-if="form.rent_status != 2" class="edit" type="text" @click="editMedia">
                  编辑
                </el-button>
              </div>
            </div>
            <div class="detail">
              <div v-if="form.rent_images == ''" class="empty">
                暂无视频图片
              </div>
              <div v-else class="media">
                <div v-for="item in imageList" :key="item" class="box">
                  <div class="mediaOut">
                    <el-image
                      alt=""
                      :preview-src-list="imageList"
                      :src="item"
                    />
                  </div>
                  <div class="icons">
                    <vab-icon
                      icon="download-cloud-2-line"
                      @click="download(item)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="完成账单" name="2">
          <div class="billTitle">
            <div class="allNum">
              <div v-if="payIncome != 0" class="income">
                收入
                <span>{{ payIncome }}</span>
              </div>
              <div v-if="payPayed != 0" class="payed">
                支出
                <span>{{ payPayed }}</span>
              </div>
            </div>
            <el-button
              v-if="
                form.rent_status == 1 ||
                form.rent_status == 3 ||
                form.rent_status == 4
              "
              @click="addpay"
            >
              添加记账
            </el-button>
          </div>
          <el-table v-loading="payListLoading" :data="payList">
            <el-table-column
              label="费用名称"
              prop="bill_title"
              show-overflow-tooltip
            />
            <el-table-column label="金额" prop="bill_money">
              <template #default="{ row }">
                <div
                  v-if="row.bill_type == 'income'"
                  v-html="'+' + row.bill_money + '元'"
                ></div>
                <div
                  v-else-if="row.bill_type == 'payed'"
                  v-html="row.bill_money + '元'"
                ></div>
              </template>
            </el-table-column>
            <el-table-column
              label="日期"
              prop="bill_date"
              show-overflow-tooltip
            />
            <el-table-column label="图片/备注" width="80">
              <template #default="{ row }">
                <div class="iconMore">
                  <el-tooltip
                    class="item"
                    content="查看图片"
                    effect="dark"
                    placement="top"
                  >
                    <span>
                      <vab-icon
                        v-if="row.bill_images != ''"
                        class="icon"
                        icon="image-2-line"
                        @click="lookImage(row)"
                      />
                    </span>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    content="查看备注"
                    effect="dark"
                    placement="top"
                  >
                    <span>
                      <vab-icon
                        v-if="row.bill_desc != ''"
                        class="icon"
                        icon="file-list-line"
                        @click="lookDesc(row)"
                      />
                    </span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="操作"
              show-overflow-tooltip
              width="60"
            >
              <template #default="{ row }">
                <el-dropdown
                  @command="
                    (value) => {
                      payMenu(value, row)
                    }
                  "
                >
                  <span class="el-dropdown-link payMenu">更多</span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="editImage">
                      编辑图片
                    </el-dropdown-item>
                    <el-dropdown-item command="editDesc">
                      编辑备注
                    </el-dropdown-item>
                    <el-dropdown-item command="deletepay">
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="querypay.page"
            :layout="layout"
            :page-size="querypay.perpage"
            :total="paytotal"
            @current-change="payPageChange"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="
            form.rent_status == 1 ||
            form.rent_status == 3 ||
            form.rent_status == 4
          "
          label="待收账单"
          name="3"
        >
          <div class="billTitle">
            <div class="allNum">
              <div v-if="paynotIncome != 0" class="income">
                待收
                <span>{{ paynotIncome }}</span>
              </div>
              <div v-if="paynotPayed != 0" class="payed">
                待付
                <span>{{ paynotPayed }}</span>
              </div>
            </div>
            <el-button @click="addpaynot">添加待收账单</el-button>
          </div>
          <el-table
            v-loading="payNotListLoading"
            :data="payNotList"
            @selection-change="setSelectRows"
          >
            <el-table-column
              align="center"
              show-overflow-tooltip
              type="selection"
            />
            <el-table-column
              label="费用名称"
              prop="bill_title"
              show-overflow-tooltip
            />
            <el-table-column label="金额" prop="bill_money">
              <template #default="{ row }">
                <div
                  v-if="row.bill_type == 'income'"
                  v-html="'+' + Number(row.bill_money).toFixed(2) + '元'"
                ></div>
                <div
                  v-else-if="row.bill_type == 'payed'"
                  v-html="'-' + Number(row.bill_money).toFixed(2) + '元'"
                ></div>
              </template>
            </el-table-column>
            <el-table-column
              label="日期"
              prop="bill_date"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="操作"
              show-overflow-tooltip
              width="85"
            >
              <template #default="{ row }">
                <el-button type="text" @click="setPayed(row)">收款</el-button>
                <el-button type="text" @click="deletepaynot(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="querypaynot.page"
            :layout="layout"
            :page-size="querypaynot.perpage"
            :total="paynottotal"
            @current-change="paynotPageChange"
          />
        </el-tab-pane>
      </el-tabs>
      <customer-info ref="customerInfo" @fetch-data="getRentDetail" />
      <customer-desc ref="customerDesc" @fetch-data="getRentDetail" />
      <customer-media ref="customerMedia" @fetch-data="getRentDetail" />
      <customer-edit ref="customerEdit" @fetch-data="getRentDetail" />
      <add-contract ref="addContract" @fetch-data="getRentDetail" />
      <did-bill ref="didBill" @fetch-data="getpayList" />
      <do-bill ref="doBill" @fetch-data="getpayNotList" />
      <set-payed ref="setPayed" @fetch-data="getpayNotList" />
      <bill-desc ref="billDesc" @fetch-data="getpayList" />
      <bill-images ref="billImages" @fetch-data="getpayList" />
      <el-image-viewer
        v-if="imageViewer"
        :on-close="closeViewer"
        :url-list="imageviewerList"
      />
      <el-dialog
        append-to-body
        title="查看备注"
        :visible.sync="dialogDescVisible"
        width="500px"
        @close="closeDesc"
      >
        <div class="desc">{{ desc }}</div>
        <template #footer>
          <el-button type="primary" @click="closeDesc">确定</el-button>
        </template>
      </el-dialog>
      <el-dialog
        append-to-body
        title="续租至"
        :visible.sync="dialogDateVisible"
        width="400px"
        @close="closeDate"
      >
        <el-form ref="dateForm" :model="dateForm" :rules="rules">
          <el-form-item label="选择时间" prop="end_date">
            <el-date-picker
              v-model="dateForm.end_date"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="请选择续租日期"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeDate">取消</el-button>
          <el-button type="primary" @click="setDate">确定</el-button>
        </template>
      </el-dialog>
    </div>
    <div v-if="selectRows.length > 0" class="drawerFooter">
      <el-button type="danger" @click="deletePayNotMore">删 除</el-button>
    </div>
  </el-drawer>
</template>

<script>
import {
  rentDetail,
  deleteCustomer,
  cancelRent,
  editRentDate,
} from '@/api/rent'
import { billList, deleteBill } from '@/api/bill'
import { getHouse } from '@/api/room'
import { downloadFile } from '@/utils/index'
import customerInfo from './components/customerInfo'
import customerDesc from './components/customerDesc'
import customerMedia from './components/customerMedia'
import customerEdit from './components/customerEdit'
import didBill from './components/didBill'
import doBill from './components/doBill'
import setPayed from './components/setPayed'
import billDesc from './components/billDesc'
import billImages from './components/billImages'
import addContract from './components/addContract'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'RentDetail',
  components: {
    customerInfo,
    customerDesc,
    customerMedia,
    customerEdit,
    didBill,
    doBill,
    setPayed,
    billDesc,
    billImages,
    addContract,
    ElImageViewer,
  },
  data() {
    return {
      sn: '',
      roomDetail: {},
      form: {},
      info: {},
      size: 640,
      title: '入住详情',
      activeName: '1',
      dialogUrl: '',
      dialogVisible: false,
      drawer: false,
      imageList: [],
      layout: 'total, prev, pager, next',
      payList: [],
      querypay: {
        page: 1,
        perpage: 10,
        is_pay: 1,
      },
      paytotal: 0,
      payIncome: 0,
      payPayed: 0,
      payListLoading: false,
      payNotList: [],
      querypaynot: {
        page: 1,
        perpage: 10,
        is_pay: 0,
      },
      paynottotal: 0,
      paynotIncome: 0,
      paynotPayed: 0,
      selectRows: [],
      payNotListLoading: false,
      imageviewerList: [],
      imageViewer: false,
      dialogDescVisible: false,
      desc: '',
      dialogDateVisible: false,
      dateForm: {
        rent_sn: '',
        end_date: '',
      },
      rules: {
        end_date: [
          { required: true, trigger: 'blur', message: '请选择续租日期' },
        ],
      },
    }
  },
  computed: {
    pickerOptions() {
      let endDateVal = this.form.end_date
      return {
        disabledDate(time) {
          return time.getTime() < new Date(endDateVal).getTime()
        },
      }
    },
  },
  methods: {
    showEdit(e) {
      this.sn = e.rent_sn
      var id = e.room_id ? e.room_id : e.id
      this.getDetail(id)
      this.getRentDetail()
      this.drawer = true
    },
    handleClick(tab) {
      if (tab.name == 1) {
        this.getRentDetail()
      } else if (tab.name == 2) {
        this.getpayList()
      } else if (tab.name == 3) {
        this.getpayNotList()
      }
    },
    payMenu(type, row) {
      console.log(type, row)
      if (type == 'editImage') {
        this.$refs['billImages'].showEdit('rent', row)
      }
      if (type == 'editDesc') {
        this.$refs['billDesc'].showEdit('rent', row)
      }
      if (type == 'deletepay') {
        this.$baseConfirm(
          '你确定要删除此账单吗，删除后，此账单将被永久清除',
          null,
          async () => {
            const { data } = await deleteBill({ bill_ids: String(row.id) })
            if (data.is_success) {
              this.$baseMessage(
                '删除成功',
                'success',
                'vab-hey-message-success'
              )
              this.getpayList()
            }
          }
        )
      }
    },
    deletepaynot(row) {
      this.$baseConfirm(
        '你确定要删除此账单吗，删除后，此账单将被永久清除',
        null,
        async () => {
          const { data } = await deleteBill({ bill_ids: String(row.id) })
          if (data.is_success) {
            this.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
            this.getpayNotList()
          }
        }
      )
    },
    deletePayNotMore() {
      this.$baseConfirm(
        '你确定要删除选中的' + this.selectRows.length + '条账单吗',
        null,
        async () => {
          const ids = this.selectRows.map((item) => item.id).join()
          const { data } = await deleteBill({ bill_ids: ids })
          if (data.is_success) {
            this.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
            this.getpayNotList()
          }
        }
      )
    },
    setSelectRows(val) {
      this.selectRows = val
    },
    lookImage(row) {
      this.imageviewerList = row.bill_images.split(',')
      this.imageViewer = true
    },
    closeViewer() {
      this.imageViewer = false
      this.imageviewerList = []
    },
    lookDesc(row) {
      this.desc = row.bill_desc
      this.dialogDescVisible = true
    },
    closeDesc() {
      this.dialogDescVisible = false
      this.desc = ''
    },
    outRoom() {
      this.$baseConfirm('退房后，房间将变成空置状态', null, async () => {
        const { data } = await cancelRent({ rent_sn: this.sn })
        if (data.is_success) {
          this.$baseMessage('退房成功', 'success', 'vab-hey-message-success')
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
    moreDate() {
      this.dateForm.rent_sn = this.sn
      this.dateForm.end_date = this.form.end_date
      this.dialogDateVisible = true
    },
    closeDate() {
      this.dialogDateVisible = false
    },
    setDate() {
      this.$refs['dateForm'].validate(async (valid) => {
        if (valid) {
          const { data } = await editRentDate(this.dateForm)
          if (data.is_success) {
            this.$baseMessage('续租成功', 'success', 'vab-hey-message-success')
            this.getRentDetail()
            this.closeDate()
          }
        }
      })
    },
    addContract() {
      this.$refs['addContract'].showEdit(this.form)
    },
    setPayed(row) {
      this.$refs['setPayed'].showEdit('rent', row)
    },
    addpay() {
      this.$refs['didBill'].showEdit('rent', this.form)
    },
    addpaynot() {
      this.$refs['doBill'].showEdit('rent', this.form)
    },
    editInfo() {
      this.$refs['customerInfo'].showEdit(this.form)
    },
    editDesc() {
      this.$refs['customerDesc'].showEdit(this.form)
    },
    editMedia() {
      this.$refs['customerMedia'].showEdit(this.form)
    },
    editCustomer(row) {
      this.$refs['customerEdit'].showEdit('edit', row)
    },
    addCustomer() {
      this.$refs['customerEdit'].showEdit('add', this.form)
    },
    deleteCustomer(row) {
      this.$baseConfirm('你确定要删除此同住人吗', null, async () => {
        const { data } = await deleteCustomer({ customer_id: row.id })
        if (data.is_success) {
          this.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
          this.getRentDetail()
        }
      })
    },
    lookMedia(item) {
      this.dialogUrl = item
      this.dialogVisible = true
    },
    download(item) {
      downloadFile(item)
    },
    close() {
      this.form = this.$options.data().form
      this.drawer = false
      this.activeName = '1'
      this.payIncome = 0
      this.payPayed = 0
      this.paynotIncome = 0
      this.paynotPayed = 0
    },
    payPageChange(val) {
      this.querypay.page = val
      this.getpayList()
    },
    paynotPageChange(val) {
      this.querypaynot.page = val
      this.getpayNotList()
    },
    async getRentDetail() {
      const { data } = await rentDetail({ rent_sn: this.sn })
      this.form = data.info
      this.imageList =
        data.info.rent_images == '' ? [] : data.info.rent_images.split(',')
      this.info = data.info.customer_info
    },
    async getpayList() {
      this.payListLoading = true
      this.querypay.rent_sn = this.sn
      const { data } = await billList(this.querypay)
      this.payList = data.bill_data.items
      this.paytotal = data.bill_data.total
      this.payIncome = data.total_money_income
      this.payPayed = data.total_money_payed
      this.payListLoading = false
    },
    async getpayNotList() {
      this.payNotListLoading = true
      this.querypaynot.rent_sn = this.sn
      const { data } = await billList(this.querypaynot)
      this.payNotList = data.bill_data.items
      this.paynottotal = data.bill_data.total
      this.paynotIncome = data.total_money_income
      this.paynotPayed = data.total_money_payed
      this.payNotListLoading = false
    },
    async getDetail(id) {
      const { data } = await getHouse({ room_id: id })
      this.roomDetail = data.info
    },
  },
}
</script>
<style lang="scss" scoped>
.header {
  padding: 0 20px 10px;
  display: flex;
  justify-content: space-between;
  .text {
    font-size: 16px;
    font-weight: bolder;
    color: rgba(0, 0, 0, 0.85);
    margin-bottom: 12px;
  }
  .group {
    font-size: 14px;
    color: #999;
  }
}
.el-tabs {
  ::v-deep .el-tabs__header {
    padding: 0 20px;
  }
  ::v-deep .el-tabs__content {
    padding: 0 20px;
  }
}
.titleBox {
  display: flex;
  justify-content: space-between;
  height: 32px;
  margin: 10px 0;
  .title {
    display: flex;
    padding-left: 16px;
    line-height: 32px;
    position: relative;
    &::after {
      content: '';
      display: block;
      position: absolute;
      width: 4px;
      height: 20px;
      background: #6898fc;
      top: 6px;
      left: 0;
      border-radius: 2px;
    }
    .titleName {
      font-size: 16px;
      font-weight: 700;
      color: rgba(0, 0, 0, 0.85);
    }
    .edit {
      color: #f5961e;
      margin-left: 16px;
    }
    .add {
      margin-left: 16px;
      i {
        color: #6898fc;
      }
    }
  }
}
.detail {
  background: #f0f7ff;
  border-radius: 8px;
  padding: 12px 16px;
  .textForm {
    display: flex;
    flex-wrap: wrap;
    .label {
      width: 50%;
      display: flex;
      height: 32px;
      line-height: 32px;
      .name {
        width: 80px;
        text-align: right;
        color: #666;
      }
      .value {
        margin-left: 10px;
        flex: 1;
        color: #3f3f3f;
      }
    }
  }
  .empty {
    color: #999;
  }
}
.billTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  .allNum {
    display: flex;
    align-items: center;
    span {
      margin-right: 20px;
      font-size: 20px;
    }
    .income span {
      color: #1ecb6b;
    }
    .payed span {
      color: #ee5959;
    }
  }
}
.iconMore {
  .icon {
    font-size: 20px;
    cursor: pointer;
    margin-right: 10px;
    color: #999;
    &:hover {
      color: #91b8ff;
    }
  }
}
.payMenu {
  color: #5187f7;
  cursor: pointer;
}
.customer {
  .empty {
    background: #f0f7ff;
    border-radius: 8px;
    padding: 12px 16px;
    color: #999;
  }
  .textList {
    .textBox {
      background: #f0f7ff;
      border-radius: 8px;
      padding: 3px 16px;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .name {
        width: 150px;
      }
      .mobile {
        width: 220px;
      }
      span {
        margin-left: 5px;
      }
      .deleteBtn {
        color: #ee5959;
      }
    }
  }
}

.media {
  display: flex;
  flex-wrap: wrap;
  .box {
    width: 90px;
    height: 90px;
    margin: 0 5px;
    margin-bottom: 10px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    .mediaOut {
      width: 90px;
      height: 90px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      position: relative;
      i {
        position: absolute;
        color: #3f3f3f;
        font-size: 30px;
        top: calc(50% - 26px);
        left: calc(50% - 15px);
      }
      ::v-deep .el-image__inner {
        width: 90px;
        height: 90px;
        object-fit: cover;
      }
      video {
        width: 90px;
        height: 90px;
        object-fit: cover;
      }
    }
    .icons {
      background: rgba(255, 255, 255, 0.9);
      height: 25px;
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        margin: 0 8px;
        color: #6898fc;
        cursor: pointer;
      }
    }
  }
}

.customerBox {
  background: #f0f7ff;
  border-radius: 8px;
  padding: 10px;
  .boxTop {
    display: flex;
    justify-content: space-between;
    .topLeft {
      .status {
        display: inline-block;
        padding: 6px 10px;
        font-size: 12px;
        line-height: 12px;
        font-weight: 500;
        color: #5187f7;
        background: #dee7ff;
        border-radius: 4px;
        margin: 0 15px 0 2px;
      }
      .name {
        display: inline-block;
        font-weight: bolder;
      }
    }
  }
  .boxBot {
    color: #999;
  }
}
.el-image-viewer__wrapper {
  z-index: 99999 !important;
}
.desc {
  height: 100px;
}
.drawerFooter {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  padding: 10px 16px;
  .el-button {
    float: right;
  }
}
</style>